package cn.wolfcode.rbac.controller;

import cn.wolfcode.rbac.domain.Employee;
import cn.wolfcode.rbac.service.LoginService;
import cn.wolfcode.rbac.util.VerifyCodeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @author xiahuihui
 * #Description LoginController
 * #Date: 2022/7/1 11:48
 */
@Controller
public class LoginController {

    @Autowired
    private LoginService loginService;

    //生成验证码
    @RequestMapping("/verifycode")
    public void verifycode(HttpServletRequest request, HttpServletResponse response){
        VerifyCodeUtil.getVerifyCode(request, response);
    }

    //登录验证
    @RequestMapping("/doLogin")
    public String doLogin(String username,String password,String verifycode,HttpServletRequest request){
        try {
            Employee login = loginService.login(username, password, verifycode, request);
            //登录成功,将当前登录的员工对象存储到session中
            HttpSession session = request.getSession();
            session.setAttribute("login",login);
        }catch (Exception e){
            e.printStackTrace();
            String errMsg = e.getMessage();
            request.setAttribute("errMsg",errMsg);
            //请求转发到登录界面
            return "forward:/login.jsp";
        }
        //重定向到/employee/list请求
        return "redirect:/employee/list";
    }
}
